from PIL import Image
import os
import sys

def compress_image(input_path, output_path, target_size_kb):
    # 将目标大小从KB转换为字节
    target_size = target_size_kb * 1024
    
    # 打开图片
    img = Image.open(input_path)
    
    # 如果是RGBA模式（带透明通道），转换为RGB
    if img.mode == 'RGBA':
        img = img.convert('RGB')
    
    # 初始质量
    quality = 95
    # 最小质量
    min_quality = 5
    
    # 第一次保存，获取初始大小
    img.save(output_path, 'JPEG', quality=quality)
    size = os.path.getsize(output_path)
    
    # 二分法查找合适的质量值
    max_quality = 95
    min_q = min_quality
    max_q = max_quality
    
    while size != target_size and quality > min_quality:
        if size > target_size:
            max_q = quality
            quality = (min_q + quality) // 2
        else:
            min_q = quality
            quality = (quality + max_q) // 2
            
        # 保存新的压缩图片
        img.save(output_path, 'JPEG', quality=quality)
        size = os.path.getsize(output_path)
        
        # 如果质量变化小于2，退出循环
        if max_q - min_q < 2:
            break
    
    # 获取最终文件大小
    final_size = os.path.getsize(output_path)
    print(f"压缩完成！")
    print(f"最终质量: {quality}")
    print(f"目标大小: {target_size_kb}KB")
    print(f"实际大小: {final_size/1024:.2f}KB")

def main():
    if len(sys.argv) != 4:
        print("使用方法: python compress_image.py <输入图片路径> <输出图片路径> <目标大小(KB)>")
        return
    
    input_path = sys.argv[1]
    output_path = sys.argv[2]
    target_size = int(sys.argv[3])
    
    if not os.path.exists(input_path):
        print("输入文件不存在！")
        return
    
    try:
        compress_image(input_path, output_path, target_size)
    except Exception as e:
        print(f"压缩过程中出错: {str(e)}")

if __name__ == "__main__":
    main()